import { redisService, REDIS_KEYS } from '../utils/redis';

/**
 * 缓存服务类
 */
export class CacheService {
  /**
   * 默认缓存过期时间（秒）
   */
  private static readonly DEFAULT_EXPIRE = 3600; // 1小时

  /**
   * 设置缓存
   */
  static async set(key: string, value: any, expireSeconds: number = this.DEFAULT_EXPIRE): Promise<void> {
    await redisService.set(key, value, expireSeconds);
  }

  /**
   * 获取缓存
   */
  static async get(key: string): Promise<any> {
    return await redisService.get(key);
  }

  /**
   * 删除缓存
   */
  static async del(key: string): Promise<number> {
    return await redisService.del(key);
  }

  /**
   * 检查缓存是否存在
   */
  static async exists(key: string): Promise<boolean> {
    return await redisService.exists(key);
  }

  /**
   * 批量删除缓存
   */
  static async delPattern(pattern: string): Promise<void> {
    const keys = await redisService.keys(pattern);
    if (keys.length > 0) {
      for (const key of keys) {
        await redisService.del(key);
      }
    }
  }

  /**
   * 获取或设置缓存（如果不存在则设置）
   */
  static async getOrSet(key: string, getter: () => Promise<any>, expireSeconds: number = this.DEFAULT_EXPIRE): Promise<any> {
    // 尝试从缓存获取
    const cached = await this.get(key);
    if (cached !== null) {
      return cached;
    }

    // 缓存不存在，执行获取函数
    const value = await getter();
    
    // 设置缓存
    if (value !== null && value !== undefined) {
      await this.set(key, value, expireSeconds);
    }

    return value;
  }

  /**
   * 清除所有缓存
   */
  static async clearAll(): Promise<void> {
    await redisService.flushdb();
  }

  /**
   * 获取缓存统计信息
   */
  static async getStats(): Promise<{
    totalKeys: number;
    memoryUsage: string;
    hitRate: number;
  }> {
    const keys = await redisService.keys('*');
    const info = await redisService.get('cache:stats') || { hits: 0, misses: 0 };
    
    return {
      totalKeys: keys.length,
      memoryUsage: 'N/A', // Redis 不直接提供内存使用信息
      hitRate: info.hits + info.misses > 0 ? info.hits / (info.hits + info.misses) : 0
    };
  }
}

/**
 * 新闻缓存服务
 */
export class NewsCacheService {
  /**
   * 获取新闻缓存键
   */
  private static getNewsKey(id: number): string {
    return `${REDIS_KEYS.CACHE_NEWS}${id}`;
  }

  /**
   * 获取新闻列表缓存键
   */
  private static getNewsListKey(params: any): string {
    const paramStr = JSON.stringify(params);
    return `${REDIS_KEYS.CACHE_NEWS}list:${Buffer.from(paramStr).toString('base64')}`;
  }

  /**
   * 缓存新闻详情
   */
  static async cacheNews(id: number, news: any, expireSeconds: number = 1800): Promise<void> {
    const key = this.getNewsKey(id);
    await CacheService.set(key, news, expireSeconds);
  }

  /**
   * 获取缓存的新闻详情
   */
  static async getCachedNews(id: number): Promise<any> {
    const key = this.getNewsKey(id);
    return await CacheService.get(key);
  }

  /**
   * 缓存新闻列表
   */
  static async cacheNewsList(params: any, list: any, expireSeconds: number = 900): Promise<void> {
    const key = this.getNewsListKey(params);
    await CacheService.set(key, list, expireSeconds);
  }

  /**
   * 获取缓存的新闻列表
   */
  static async getCachedNewsList(params: any): Promise<any> {
    const key = this.getNewsListKey(params);
    return await CacheService.get(key);
  }

  /**
   * 清除新闻相关缓存
   */
  static async clearNewsCache(id?: number): Promise<void> {
    if (id) {
      // 清除特定新闻的缓存
      const newsKey = this.getNewsKey(id);
      await CacheService.del(newsKey);
    }
    
    // 清除所有新闻列表缓存
    await CacheService.delPattern(`${REDIS_KEYS.CACHE_NEWS}list:*`);
  }
}

/**
 * 分类缓存服务
 */
export class CategoryCacheService {
  /**
   * 获取分类缓存键
   */
  private static getCategoryKey(id: number): string {
    return `${REDIS_KEYS.CACHE_CATEGORY}${id}`;
  }

  /**
   * 获取分类树缓存键
   */
  private static getCategoryTreeKey(): string {
    return `${REDIS_KEYS.CACHE_CATEGORY}tree`;
  }

  /**
   * 缓存分类详情
   */
  static async cacheCategory(id: number, category: any, expireSeconds: number = 3600): Promise<void> {
    const key = this.getCategoryKey(id);
    await CacheService.set(key, category, expireSeconds);
  }

  /**
   * 获取缓存的分类详情
   */
  static async getCachedCategory(id: number): Promise<any> {
    const key = this.getCategoryKey(id);
    return await CacheService.get(key);
  }

  /**
   * 缓存分类树
   */
  static async cacheCategoryTree(tree: any, expireSeconds: number = 1800): Promise<void> {
    const key = this.getCategoryTreeKey();
    await CacheService.set(key, tree, expireSeconds);
  }

  /**
   * 获取缓存的分类树
   */
  static async getCachedCategoryTree(): Promise<any> {
    const key = this.getCategoryTreeKey();
    return await CacheService.get(key);
  }

  /**
   * 清除分类相关缓存
   */
  static async clearCategoryCache(id?: number): Promise<void> {
    if (id) {
      // 清除特定分类的缓存
      const categoryKey = this.getCategoryKey(id);
      await CacheService.del(categoryKey);
    }
    
    // 清除分类树缓存
    const treeKey = this.getCategoryTreeKey();
    await CacheService.del(treeKey);
  }
}

/**
 * 用户缓存服务
 */
export class UserCacheService {
  /**
   * 获取用户缓存键
   */
  private static getUserKey(id: number): string {
    return `${REDIS_KEYS.CACHE_USER}${id}`;
  }

  /**
   * 获取用户会话键
   */
  private static getUserSessionKey(token: string): string {
    return `${REDIS_KEYS.USER_SESSION}${token}`;
  }

  /**
   * 缓存用户信息
   */
  static async cacheUser(id: number, user: any, expireSeconds: number = 1800): Promise<void> {
    const key = this.getUserKey(id);
    await CacheService.set(key, user, expireSeconds);
  }

  /**
   * 获取缓存的用户信息
   */
  static async getCachedUser(id: number): Promise<any> {
    const key = this.getUserKey(id);
    return await CacheService.get(key);
  }

  /**
   * 缓存用户会话
   */
  static async cacheUserSession(token: string, session: any, expireSeconds: number = 7200): Promise<void> {
    const key = this.getUserSessionKey(token);
    await CacheService.set(key, session, expireSeconds);
  }

  /**
   * 获取缓存的用户会话
   */
  static async getCachedUserSession(token: string): Promise<any> {
    const key = this.getUserSessionKey(token);
    return await CacheService.get(key);
  }

  /**
   * 删除用户会话
   */
  static async deleteUserSession(token: string): Promise<number> {
    const key = this.getUserSessionKey(token);
    return await CacheService.del(key);
  }

  /**
   * 清除用户相关缓存
   */
  static async clearUserCache(id?: number): Promise<void> {
    if (id) {
      // 清除特定用户的缓存
      const userKey = this.getUserKey(id);
      await CacheService.del(userKey);
    }
  }
}

/**
 * 统计缓存服务
 */
export class StatsCacheService {
  /**
   * 增加浏览量
   */
  static async incrementViews(newsId: number): Promise<number> {
    const key = `${REDIS_KEYS.STATS_VIEWS}${newsId}`;
    return await redisService.incr(key);
  }

  /**
   * 获取浏览量
   */
  static async getViews(newsId: number): Promise<number> {
    const key = `${REDIS_KEYS.STATS_VIEWS}${newsId}`;
    const views = await redisService.get(key);
    return views || 0;
  }

  /**
   * 增加访问量
   */
  static async incrementVisits(page: string): Promise<number> {
    const key = `${REDIS_KEYS.STATS_VISITS}${page}`;
    return await redisService.incr(key);
  }

  /**
   * 获取访问量
   */
  static async getVisits(page: string): Promise<number> {
    const key = `${REDIS_KEYS.STATS_VISITS}${page}`;
    const visits = await redisService.get(key);
    return visits || 0;
  }

  /**
   * 获取所有统计数据
   */
  static async getAllStats(): Promise<{
    views: Record<string, number>;
    visits: Record<string, number>;
  }> {
    const viewKeys = await redisService.keys(`${REDIS_KEYS.STATS_VIEWS}*`);
    const visitKeys = await redisService.keys(`${REDIS_KEYS.STATS_VISITS}*`);

    const views: Record<string, number> = {};
    const visits: Record<string, number> = {};

    // 获取浏览量数据
    for (const key of viewKeys) {
      const newsId = key.replace(REDIS_KEYS.STATS_VIEWS, '');
      const count = await redisService.get(key);
      views[newsId] = count || 0;
    }

    // 获取访问量数据
    for (const key of visitKeys) {
      const page = key.replace(REDIS_KEYS.STATS_VISITS, '');
      const count = await redisService.get(key);
      visits[page] = count || 0;
    }

    return { views, visits };
  }
} 